const winston = require('../utils/winstonLogger.js');
const mongoose = require('mongoose');
const orderInfoModel = mongoose.model("OrderInfo");

module.exports = {
    addOrderInfo : addOrderInfo,
    updateOrderInfo : updateOrderInfo,
    deleteOrderInfo: deleteOrderInfo,
    queryOrderInfo : queryOrderInfo,
    addOrder: addOrder,
    findOrderInfoByCustomerId: findOrderInfoByCustomerId
}



function addOrderInfo (orderInfos,callback) {
    orderInfoModel.insertMany(orderInfos,function(error,docs){
        if(error){
            winston.error(error);
            return  callback(error,null);
        }
        else{
            console.log(docs);
            return  callback(null,docs);
        }
    })
}

function addOrder(order,callback){
    var o = new orderInfoModel(order);
    o.save(function(err,doc){
        if(err){
            winston.error(err);
            callback(err,null);
        }else{
            callback(null,doc);
        }
    });
}

function deleteOrderInfo (orderInfoId,callback) {
    orderInfoModel.deleteMany({_id:orderInfoId},function(error,docs){
        if(error){
            winston.error(error);
            return  callback(error,null);
        }
        else{
            console.log(docs);
            return  callback(null,docs);
        }
    })
}

function updateOrderInfo (newOrderInfo,callback) {
    orderInfoModel.updateMany({_id:newOrderInfo._id},newOrderInfo,function(error,docs){
        if(error){
            winston.error(error);
            return  callback(error,null);
        }
        else{
            console.log(docs);
            return  callback(null,docs);
        }
    })
}

function queryOrderInfo ($n={},callback){
    orderInfoModel.find($n,function(error,docs){
        if(error){
            winston.error(error);
            return  callback(error,null);
        }
        else{
            console.log(docs);
            return  callback(null,docs);
        }
    }).populate('customer')
        .populate('foods.food');
}


function findOrderInfoByCustomerId(customerId,callback){
    orderInfoModel.find({'customer':customerId},function(err,data){
       if (err) return console.error(err);
         else{
             callback(null,data);
             // return console.log(result);
         } 
    })
     .populate('merchant')
     .populate('customer')
     .populate('foods')
     .exec();
     // callback(null,data);
 }
 
